﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class VerycdLogin : LoginImplBase
    {
        public VerycdLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string loginurl = "http://game.verycd.com/proxy?url=/signin";
            string data = String.Format("continue=http%3A%2F%2Fgame.verycd.com%2Fas%2F&login_submit=%E7%99%BB%E5%BD%95&username={0}&password={1}", _username, _password);
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("X-Requested-With", "XMLHttpRequest");

            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies, "http://game.verycd.com/as/", headers);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string retstr = resp.getContent();
            //{"status":"ok"}   {"status":false,"msg":"loginFail","info":"...."}
            if (retstr.IndexOf("\"status\":false") >= 0)
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            string redirecturl = String.Format("http://secure.verycd.com/signin?ak=astd&sid=S{0}", _acc.ServerId);
            resp = TransferMgr.doGetPure(redirecturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
            string location = resp.getExtraHeader("Location");
            if (location == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

            resp = TransferMgr.doGetPure(location, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
            string content = resp.getContent();
            Regex re = new Regex(".*document\\.getElementById\\(\"play_frame\"\\)\\.src=\"([^\"']*?)\";.*");
            Match m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }

            string gameurl = m.Groups[1].Value;
            processStartGame(gameurl, result, ref cookies);
            return result;
        }
    }
}
